<template>
  <div class="contract-terms">
    <div >
      <Editor
        v-model="richTextContent"
        :height="400"
        :readonly="!isShowSubBut"
        @change="handleRichTextChange"
      />
    </div>
<!--    <div v-else>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="TermID" label="条款ID" width="180">
          <template #default="scope">
            <el-select
              v-model="scope.row.TermID"
              filterable
              remote
              reserve-keyword
              :placeholder="`请选择${title}`"
              style="width: 100%"
              @change="e => updateTermContent(e, scope.row)"
              :disabled="!isShowSubBut"
            >
              <el-option
                v-for="item in listTypeInfo"
                :key="item.Id"
                :label="item.Content"
                :value="item.Id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TermContent" label="条款内容">
          <template #default="scope">
            <el-input
              type="textarea"
              v-model="scope.row.TermContent"
              :rows="3"
              @change="e => updateTermContent(e,scope.row)"
              :disabled="!isShowSubBut"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="isShowSubBut">
          <template #default="scope">
            <el-button type="danger" @click="removeTerm(scope.$index)" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addTerm" :disabled="!isShowSubBut" class="mt-4">
        添加条款
      </el-button>
    </div>-->
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { ElButton, ElInput, ElOption, ElSelect, ElTable, ElTableColumn, ElMessage } from 'element-plus'
import { Editor } from '@/components/Editor'
import { GetTK } from '@/api/base'
import { debounce } from '@/utils/util'
import { checkFildsStore } from '@/stores/modules/checkFilds'

const props = defineProps({
  Trem: {
    type: Array,
    default: () => []
  },
  Id: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  isBg: {
    type: Boolean,
    default: false
  },
  isShowSubBut: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:Trem'])

const listTypeInfo = ref([])
const richTextContent = ref('')
const internalTableData = ref([])

const tableData = computed(() => internalTableData.value)

const getTermContent = debounce(async () => {
  try {
    const { Data } = await GetTK({ Code: props.Id, Name: '' })
    listTypeInfo.value = Data
  } catch (error) {

  }
}, 300)

function updateTermContent(termId, term) {
  const selectedTerm = listTypeInfo.value.find(item => item.Id === termId)
  if (selectedTerm) {
    term.TermContent = selectedTerm.Content
    debouncedEmit()
  }
  else {
    debouncedEmit()
  }
}

const checkFild = checkFildsStore()

// 错误校验提示
const validateError = list => {
  list.forEach(val => {
    setTimeout(() => {
      ElMessage.error(`${props.title}是必填项！`)
      checkFild.setData(val)
    }, 100)
  })
}

function addTerm() {
  internalTableData.value.push({ TermID: '', TermContent: '' })
  debouncedEmit()
}

function removeTerm(index) {
  internalTableData.value.splice(index, 1)
  debouncedEmit()
}

const debouncedEmit = debounce(() => {
  emit('update:Trem', internalTableData.value)
}, 500)

function handleRichTextChange(content) {
  richTextContent.value = content
  internalTableData.value =[]
  internalTableData.value.push({ TermID: '', TermContent: content })
  debouncedEmit()
}


const validateTable = () => {
  if (props.isBg) {
    return internalTableData.value.every(term => term.TermID && term.TermContent)
  } else {
    return richTextContent.value.trim() !== ''
  }
}

//监听

watch(() => props.Trem, newValue => {
  // richTextContent.value = ''
  if (props.isBg) {
    internalTableData.value = JSON.parse(JSON.stringify(newValue))
  } else {
    if (newValue.length>0){
      richTextContent.value = newValue.map(term => term.TermContent).join('\n')
    }
  }
  // console.log(props.isBg,"q23223")
}, { deep: true, immediate: true })

onMounted(() => {
  getTermContent()
})

defineExpose({ validateTable })
</script>

<style scoped>
.contract-terms {
  max-width: 1000px;
  margin: 0 auto;
}

.mt-4 {
  margin-top: 16px;
}
</style>


